<?php


namespace App\Http\Controllers\user;


use App\Engine\BaseController;
use App\Engine\TokenService;
use App\Exceptions\ApiException;
use App\Http\service\GzhService;
use App\Http\service\XcxService;
use App\Models\BindGood;
use App\Models\Chicken;
use App\Models\Chicken as ChickenModel;
use App\Models\EggLog;
use App\Models\Sys as SysModel;
use App\Models\ShareLog as ShareLogModel;
use App\Models\UserBindGoods;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use function app\Utils\go;
use App\Models\StarLog as StarLogModel;
use App\Models\User as UserModel;
use App\Models\FeedsLog as FeedsLogModel;
use App\Models\Tree as TreeModel;
use App\Models\TreeLog as TreeLogModel;
use App\Models\BindInvite as BindInvitemodel;
use App\Models\BindGood as BindGoodsModel;


//用户任务
class Task extends BaseController
{

    public function get_all_bind_goods()
    {
        $res=BindGoodsModel::get();
        return go($res);
    }

    /**
     * 获取用户盲盒商品
     */
    public function get_user_bind_goods()
    {
        $res=UserBindGoods::where(["uid"=>TokenService::getCurrentUid(),"state"=>$this->get["state"]])->paginate($this->get["num"]);
        return go($res);
    }

    public function get_bind_progress()
    {
        $invite_sum=SysModel::getValue("box_invite_user");
        $now=BindInvitemodel::where(["uid"=>TokenService::getCurrentUid(),'state'=>0])->count();
        $data=[
            "total"=>$invite_sum,
            "now"=>$now
        ];
        return go($data);
    }


    /**
     * 开始盲盒游戏
     */
    public function start_bind_box()
    {
        $bindGoodsModel=new BindGood();
        $bindGoodsModel->checkStock();
        $res=Cache::lock("bind_box_start")->get(function ()use($bindGoodsModel){
            $is_get=UserBindGoods::where(["uid"=>TokenService::getCurrentUid()])->count();
            $share=ShareLogModel::where("uid",TokenService::getCurrentUid())->count();
            $invite_sum=SysModel::getValue("box_invite_user");
            $bind_box_limit=SysModel::getValue("bind_box_limit");
            if ($is_get>$share)
                throw new ApiException("每个用户只能获得一次盲盒，分享可获得更多机会");

            if ($bind_box_limit<=$is_get)
                throw new ApiException("今日抽奖次数已限制");


            $goods=$bindGoodsModel->where("num",">",0)->inRandomOrder()->first();
            if (!$goods){
                throw new ApiException("活动已结束");
            }
            $is_invite=BindInvitemodel::where(["uid"=>TokenService::getCurrentUid(),'state'=>0])->count();

            if ($invite_sum>$is_invite)
                throw new ApiException("邀请助力人数不足");
            DB::beginTransaction();
            try {
                BindInvitemodel::where(["uid"=>TokenService::getCurrentUid(),'state'=>0])->update(["state"=>1]);
                $create=[
                    "uid"=>TokenService::getCurrentUid(),
                    "bind_id"=>$goods["id"],
                    "date"=>date("Y-m-d"),
                    "state"=>0
                ];
                $res=UserBindGoods::create($create);
                $bindGoodsModel->where("id",$goods["id"])->decrement("num");
                DB::commit();
                return $goods;
            }catch (\Exception $exception){
                DB::rollBack();
                throw new ApiException($exception->getMessage());
            }
        });
        return go($res);
    }

    /**创建盲盒二维码
     * @return array
     * @throws ApiException
     */
    public function create_bind_box_qrcode()
    {
        $userModel=new UserModel();
        $user=$userModel->where("id",TokenService::getCurrentUid())->first();
        if (!$user["bind_box_qrcode"]){
            $scene="type=invite_bind_box&id=".TokenService::getCurrentUid();
            $qrcode=(new XcxService())->create_xcx_code($scene);
            $res=$userModel->where("id",TokenService::getCurrentUid())->update(["bind_box_qrcode"=>$qrcode]);
        }
        $user=$userModel->where("id",TokenService::getCurrentUid())->first();
        return go($user);

    }

    /**查看个人盲盒邀请情况
     * @return array
     */
    public function get_bind_box_detail()
    {
        $res=BindInvitemodel::where(["uid"=>TokenService::getCurrentUid(),"date"=>date("Y-m-d")])->get();
        return go($res);
    }

    /**盲盒邀请绑定
     * @return array
     */
    public function bind_box_invite()
    {
        $uid=TokenService::getCurrentUid();
        $res=Cache::lock($uid."_check_bind")->get(function ()use($uid){
            $is_invite=BindInvitemodel::where(["invite_id"=>$uid,"date"=>date("Y-m-d")])->count();

            if($is_invite>=3){
                throw new ApiException("一个用户一天只能助力三次");
            }
            $count=BindInvitemodel::where(["uid"=>$this->get["uid"], "date"=>date("Y-m-d")])->count();
            $sys=SysModel::getValue("box_invite_user");
            if ($count>=$sys){
                throw new ApiException("邀请人数已满");
            }
            $create=[
                "uid"=>$this->get["uid"],
                "invite_id"=>$uid,
                "date"=>date("Y-m-d"),
                "state"=>0
            ];
            $res=BindInvitemodel::create($create);
            return $res;
        });
        return go($res);
    }

    /**
     * 领取红包
     */
    public function get_red_packet()
    {
        $uid=TokenService::getCurrentUid();
        $res=Cache::lock("red_".$uid)->get(function (){
            $sys=SysModel::get_sys_type(5);
            $tree=TreeModel::where("uid",TokenService::getCurrentUid())->first();
            if(($tree["now_tice"]<$sys["tree_total"])&&$tree["total_money"]!=0)
                throw new ApiException("浇水次数不够");
            DB::rollBack();
            try {
                $price=$this->randFloat($sys["tree_min_price"],$sys["tree_max_price"]);
                TreeModel::where("id",$tree["id"])->update(["state"=>0,"now_tice"=>0]);
                TreeModel::where("id",$tree["id"])->increment("total_money",$price);
                UserModel::where("id",TokenService::getCurrentUid())->increment("balance",$price);
                $create_log=[
                    "uid"=>TokenService::getCurrentUid(),
                    "tree_id"=>$tree["id"],
                    "date"=>date("Y-m-d"),
                    "type"=>1,
                    "content"=>"领取红包获得金额:{$price}元"
                ];
                TreeLogModel::create($create_log);
                $res=TreeModel::where("id",$tree["id"])->first();
                $res["get_price"]=$price;
                DB::commit();
                return $res;
            }catch (\Exception $exception){
                DB::rollBack();
                throw new ApiException($exception->getMessage());
            }
        });
        return go($res);
    }

   private function randFloat($min = 0, $max = 1) {
        $rand = $min + mt_rand() / mt_getrandmax() * ($max - $min);
        return floatval(number_format($rand,2));
    }

    /**
     * 发财树浇水
     */
    public function update_tree()
    {

        $uid=TokenService::getCurrentUid();
        $user=UserModel::where("id",TokenService::getCurrentUid())->first();
        $tree=TreeModel::where(["uid"=>$uid])->first();
        if (!$tree)
            throw new ApiException("系统错误");
        if ($tree["state"]==2){
            throw new ApiException("请先领取红包");
        }
        $sys=SysModel::get_sys_type(5);
        if ($user["tree"]<1){
            throw new ApiException("浇水次数不够");
        }
       DB::beginTransaction();
        try {
            if($tree["now_tice"]+1<$sys["tree_change"]){
                $state=0;
            }else{
                $state=1;
            }
            if ($tree["now_tice"]+1>=$sys["tree_total"]){
                $state=2;
            }
            TreeModel::where(["id"=>$tree["id"]])->update(["state"=>$state]);
            TreeModel::where(["id"=>$tree["id"]])->increment("now_tice",1);
            $create_log=[
                "tree_id"=>$tree["id"],
                "date"=>date("Y-m-d"),
                "uid"=>TokenService::getCurrentUid(),
                "content"=>"发财树浇水一次",
                "type"=>0
            ];
            $res=TreeLogModel::create($create_log);
            $res=TreeModel::where(["id"=>$tree["id"]])->first();
            $user->decrement("tree",1);
            DB::commit();
            return go($res);
        }catch (\Exception $exception){
            DB::rollBack();
            throw new ApiException($exception->getMessage());
        }
    }

    /**获取发财树
     * @return array
     */
    public function get_tree()
    {
        $tree=new TreeModel();
        $res=TreeModel::where("uid",TokenService::getCurrentUid())->first();
        if (!$res){
            $create=[
                "uid"=>TokenService::getCurrentUid(),
                "now_tice"=>0,
                "state"=>0,
                "total_money"=>0
            ];
            $tree->create($create);
            $res=TreeModel::where("uid",TokenService::getCurrentUid())->first();
        }
        return go($res);
    }

    public function is_tree()
    {
        $res=TreeModel::where("uid",TokenService::getCurrentUid())->first();
        $flag=false;
        if($res){
            $flag=true;
        }
        return go(["data"=>$flag]);
    }

    /**
     * 获取任务
     */
    public function get_task()
    {
        $sys = new SysModel();
        $shareLog = new ShareLogModel();
        $chicken = ChickenModel::where("uid", TokenService::getCurrentUid())->first();
        if ($chicken) {
            $value = 1;
        } else {
            $value = 0;
        }
        $res = array();
        $res[] = [
            "title" => "领养小鸡",
            "value" => $value,
            "total" => 1,
            "reward" => "小鸡1只",
            "path" => "/pages/chick/chick",
        ];
        $share_get_draw_limit = $sys->get_Value("share_get_draw_limit");
        $share_get_draw = $sys->get_Value("share_get_draw");
        $user_share = $shareLog->where(["uid" => TokenService::getCurrentUid(), "date" => date("Y-m-d")])->count();
        $res[] = [
            "title" => "每日分享",
            "value" => $user_share,
            "total" => $share_get_draw_limit,
            "reward" => "抽奖次数*{$share_get_draw}",
            "path" => "/pages/prize/prize"
        ];
        if ($chicken) {
            $res[] = [
                "title" => "喂养小鸡",
                "value" => $chicken["food"],
                "total" => $chicken["limit"],
                "reward" => "鸡蛋",
                "path" => "/pages/chick/chick"
            ];
        }
        return go($res);
    }


    /**
     * 点赞项目
     */
    public function star_project()
    {
        $star_log=new StarLogModel();
        $where=[
            'uid'=>TokenService::getCurrentUid(),
            'house_id'=>$this->get["id"],
            "invite_uid"=>$this->get["invite_uid"]
        ];
        $res=$star_log->where($where)->first();
        if ($res)
            throw new ApiException("已点赞过");
        $res=$star_log->create($where);
        return go($res);
    }

    /**
     * 判断用户是否有小鸡
     */
    public function is_chiken()
    {
        $check=ChickenModel::where("uid",TokenService::getCurrentUid())->first();
        $data=[
            "data"=>true
        ];
        if (!$check){
            $data["data"]=false;
        }
        return go($data);
    }

    /**获取小鸡信息
     * @return array
     * @throws ApiException
     */
    public function get_chicken()
    {
        $check=ChickenModel::where("uid",TokenService::getCurrentUid())->first();
        if (!$check){
            $create=[
                "uid"=>TokenService::getCurrentUid(),
                "grade"=>0,
                "experience"=>0,
                "food"=>0,
                "rank"=>0,
                "consume_food"=>0,
                "hunger"=>0,
                "limit"=>SysModel::getValue("feed_time")
            ];
            $uid=TokenService::getCurrentUid();
            UserModel::where("id",$uid)->increment("egg",1);
            $check=ChickenModel::create($create);
        }
        return go($check);
    }

    /**
     * 喂养小鸡
     */
    public function feed_chicken()
    {
        DB::beginTransaction();
        try {
            $chicken=ChickenModel::where("uid",TokenService::getCurrentUid())->first();
            $user=UserModel::where("id",TokenService::getCurrentUid())->first();
            $count=FeedsLogModel::where(["uid"=>TokenService::getCurrentUid(),"date"=>date("Y-m-d")])->count();
            if ($chicken["limit"]<=$count)
                throw new ApiException("今日喂养次数已上限");
            if($user["food"]<1){
                throw new ApiException("饲料不足，浏览楼盘信息获取饲料");
            }

            Chicken::find($chicken["id"])->increment("experience",1);
            Chicken::find($chicken["id"])->increment("food",1);
            $res=UserModel::where("id",TokenService::getCurrentUid())->decrement("food",1);
            $log=[
                "uid"=>TokenService::getCurrentUid(),
                "num"=>1,
                "content"=>"喂养小鸡1次",
                "date"=>date("Y-m-d")
            ];
            $res=FeedsLogModel::create($log);
            DB::commit();
            return go($res);
        }catch (\Exception $exception){
            DB::rollBack();
            throw new ApiException($exception->getMessage());
        }
    }

    /**id获取日志
     * @return mixed
     */
    public function get_egglog_id()
    {
        $res=Cache::lock("egg_log")->get(function (){
            $res=EggLog::where("id",$this->get["id"])->first();
            return $res;
        });
        return go($res);
    }

    /**
     * 申请领取鸡蛋
     */
    public function application_egg()
    {
        $min_get_egg=SysModel::getValue("min_get_egg");
        $user=UserModel::where("id",TokenService::getCurrentUid())->first();
        if(!isset($user["egg"])){
            $user["egg"]=0;
        }


        if($user["egg"]<$min_get_egg)
            throw new ApiException("当前鸡蛋剩余{$user['egg']}个，满{$min_get_egg}个以上即可领取");
        DB::beginTransaction();
        try {
            $egg=$user["egg"];
            $user->decrement("egg",$egg);
            $log=[
                "uid"=>TokenService::getCurrentUid(),
                "type"=>1,
                "num"=>$egg,
                "state"=>0
            ];
           $res= EggLog::create($log);
            DB::commit();
            return go($res);
        }catch (\Exception $exception)
        {
            DB::rollBack();
        }
    }
}
